package com.example.yx.demo20;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

public class A20 {
    private static final Logger log = LoggerFactory.getLogger(A20.class);

    public static void main(String[] args) throws Exception {
        AnnotationConfigServletWebServerApplicationContext context
                = new AnnotationConfigServletWebServerApplicationContext(WebConfig.class);

        //解析@RequestMapping以及它的一些派生注解，生成路径与控制器方法的映射关系，在初始化时就生成
        RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);

        //获取映射结果
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        handlerMethods.forEach((k,v) ->{
            System.out.println(k + " = " + v);
        });

        //请求来了，获取控制器方法 ,返回一个处理器执行链对象
        MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test4");
        request.setParameter("name","张三");
        request.addHeader("token","某个令牌");
        MockHttpServletResponse response = new MockHttpServletResponse();
        HandlerExecutionChain get = handlerMapping.getHandler(request);
//
//        System.out.println(get);

        MyRequestMappingHandlerAdapter handlerAdapter = context.getBean(MyRequestMappingHandlerAdapter.class);
        handlerAdapter.invokeHandlerMethod(request,response, ((HandlerMethod) get.getHandler()));

        //检查响应对象是否有yml结果
        System.out.println(response.getContentAsString());
//        System.out.println("---------------------------------参数解析器------------");
//        for (HandlerMethodArgumentResolver resolver : handlerAdapter.getArgumentResolvers()) {
//            System.out.println(resolver);
//        }
//
//
//        System.out.println("---------------------------------返回值解析器------------");
//        for (HandlerMethodReturnValueHandler resolver : handlerAdapter.getReturnValueHandlers()) {
//            System.out.println(resolver);
//        }

    }
}
